<?php

namespace app\lib\token;

use app\exception\Err;
use app\lib\Helper;
use think\facade\Cache;
use think\facade\Env;

class Token {

    protected $token;
    protected $cacheKey;
    protected $cacheExp;
    protected $values;
    protected $cache;

    function __construct(string $token = ''){
        $this->token = empty($token) ? md5(Helper::uniID()) : $token;
        $this->cacheKey = Env::get('TOKEN.PREFIX','tk') . '_' . $this->token;
        $this->cacheExp =  Env::get('TOKEN.EXP', 7200);
        $this->cache = Cache::store('token');
    }

    /**
     * 将数据存到Token
     *
     * @param array $values
     * @return string
     */
    public function set($values){
        $values['exp_time'] = time() + $this->cacheExp; // 过期时间
        if (! $this->cache->set($this->cacheKey, $values, $this->cacheExp))  {
            throw new Err('缓存写入失败');
        }
        return $this->token;
    }

    /**
     * 获取token中的数据
     *
     * @param string $token
     * @param string $field
     * @return array|false|string
     */
    public function get(string $field = ''){
        $vars = $this->cache->get($this->cacheKey);
        if (empty($vars)) {
            return false;
        }
        $vars = is_array($vars) ? $vars : json_decode($vars, true);
        if(! empty($field)){
            return array_key_exists($field, $vars)? $vars[$field]: '';
        }else{
            return $vars;
        }
    }

    /**
     * 删除
     *
     * @return bool
     */
    public function delete(){
        return $this->cache->delete($this->cacheKey);
    }

    /**
     * 给一个token续命
     *
     * @param integer $time 过期时间
     * @return string
     */
    public function alive(int $time = 300){
        $vars = $this->get();
        $this->cacheExp = $time;
        $this->set($vars);
        return $this->token;
    }

}
